/*
 *  Copyright 1999-2021 Seata.io Group.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.deng.seata.at.account.service;

import com.deng.seata.at.account.dao.mapper.AccountMapper;
import com.deng.seata.at.account.dao.po.Account;
import com.deng.seata.at.account.facade.AccountFacade;
import com.deng.seata.at.account.facade.request.AccountRequest;
import com.deng.seata.at.account.facade.response.AccountResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Service("accountFacade")
public class AccountFacadeImpl implements AccountFacade {

    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AccountResponse transfer(AccountRequest request) {
        Account dbAccount = accountMapper.selectById(request.getUserId());
        if (Objects.isNull(dbAccount) || dbAccount.getBalance() < request.getAmount()) {
            throw new RuntimeException("账户为空或者余额不足");
        }

        dbAccount.setId(request.getUserId());
        dbAccount.setFreezeAmount(dbAccount.getFreezeAmount() + request.getAmount()); // 增加冻结金额

        int count = accountMapper.updateById(dbAccount);
        if(count <= 0){
            throw new RuntimeException("转账失败！");
        }
        AccountResponse response= new AccountResponse();
        response.setCode("1000");
        response.setMessage("成功");
        return response;
    }


}